//
//  WeakTableViewController.m
//  ExerciseOC
//
//  Created by 王子曦 on 2025/4/14.
//

#import "WeakTableViewController.h"

@interface WeakTableViewController ()
@property (nonatomic, strong) UITextView *textView;
@end

@implementation WeakTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"弱引用表";
    
    // 创建文本视图
    self.textView = [[UITextView alloc] initWithFrame:self.view.bounds];
    self.textView.editable = NO;
    self.textView.font = [UIFont systemFontOfSize:16];
    [self.view addSubview:self.textView];
    
    // 设置内容
    NSMutableString *content = [NSMutableString string];
    [content appendString:@"弱引用表（Weak Reference Table）是iOS中管理weak指针的重要机制\n\n"];
    
    [content appendString:@"1. 弱引用表的作用：\n"];
    [content appendString:@"   - 管理所有weak指针\n"];
    [content appendString:@"   - 在对象释放时将weak指针置为nil\n"];
    [content appendString:@"   - 防止野指针的产生\n\n"];
    
    [content appendString:@"2. 工作原理：\n"];
    [content appendString:@"   - 系统维护全局weak表\n"];
    [content appendString:@"   - 使用Hash表存储weak指针\n"];
    [content appendString:@"   - 对象地址作为key\n"];
    [content appendString:@"   - weak指针地址作为value\n\n"];
    
    [content appendString:@"3. 使用场景：\n"];
    [content appendString:@"   - delegate代理对象\n"];
    [content appendString:@"   - 避免循环引用\n"];
    [content appendString:@"   - 父子视图控制器\n"];
    [content appendString:@"   - 临时引用对象\n\n"];
    
    [content appendString:@"4. 代码示例：\n"];
    [content appendString:@"   id obj = [[NSObject alloc] init];\n"];
    [content appendString:@"   __weak id weakObj = obj;  // 加入weak表\n"];
    [content appendString:@"   obj = nil;  // 对象释放，weak表中的指针自动置nil\n\n"];
    
    [content appendString:@"5. 注意事项：\n"];
    [content appendString:@"   - weak指针自动置nil是线程安全的\n"];
    [content appendString:@"   - 不要过度使用weak引用\n"];
    [content appendString:@"   - weak不会产生引用计数\n"];
    [content appendString:@"   - 访问weak对象前最好判空"];
    
    self.textView.text = content;
}

@end